import React, { memo } from 'react';
import { Select, Dept } from '@block/plug';
import { SelectProps } from '@block/plug/lib/select/Select';
import { $fetch, isEqual } from '@block/utils';
import './EmpSelect.scss';
import Url from './url';

/**
 * 搜人下拉组件
 */
interface Props extends DefaultToEditItem, SelectProps {
  onChange?: (val: EmpOption[]) => void;
  mode?: Mode;
  value?: EmpOption[];
  lineBreak?: Boolean;
}

const EmpSelect = (props: Props) => {
  const { onChange, mode, value, placeholder, popLayer, lineBreak } = props;

  const handleOnChange = (option?: EmpOption[]) => {
    onChange(option);
  };

  const renderOptionContent = (option?: EmpOption) => {
    return (
      <div className="emp-select-option">
        <div className="emp-select-option-name">
          {option.name}/{option.misId}
        </div>
        <div className="emp-select-option-org">
          <Dept label={option.orgPathName} separate="/" />
        </div>
      </div>
    );
  };

  const handleOrgPathName = (orgPathName: string) => {
    /** orgPathName 超过两个/ ...替换 */
    const count = (orgPathName?.match(/\//g) || []).length;
    if (count > 2) {
      const orgPathNameArr = orgPathName?.split('/');
      return `${orgPathNameArr[0]}/.../${orgPathNameArr[orgPathNameArr.length - 1]}`;
    }
    return orgPathName;
  };

  const renderView = () => {
    if (value?.length > 0) {
      return value.map((emp, index) => {
        return (
          <span>
            {lineBreak ? (
              <div className="emp-select-view">
                {emp?.name}-{handleOrgPathName(emp?.orgPathName)}
              </div>
            ) : (
              <>
                {index > 0 && ','}
                {emp?.name}-{handleOrgPathName(emp?.orgPathName)}
              </>
            )}
          </span>
        );
      });
    }
    return '-';
  };

  return (
    <div className="emp-select">
      {mode === 'edit' ? (
        <Select
          placeholder={placeholder}
          keyField="empId"
          labelField="name"
          multiple
          value={value}
          onChange={handleOnChange}
          dispatchFetchDataWithoutKeyword={false}
          onFetchData={(search) => {
            return $fetch(Url.queryEmployeeList, {
              search: search?.trim(),
            });
          }}
          optionLabelProp="name"
          renderOptionContent={renderOptionContent}
          popLayer={popLayer}
        />
      ) : (
        renderView()
      )}
    </div>
  );
};

const propsEqual = (prevProps: Props, nextProps: Props) => {
  return isEqual(prevProps.value, nextProps.value) && isEqual(prevProps.mode, nextProps.mode);
};
export default memo(EmpSelect, propsEqual);
